package com.atguigu.gmall.activity.listener;

import com.atguigu.gmall.activity.service.SeckillOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 秒杀订单支付成功消息监听器
 */
@Component
@Slf4j
public class SeckillOrderPayListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 接收消息，修改秒杀订单的状态
     */
    @RabbitListener(queues = "order_pay_seckill_queue")
    public void listenerSeckillOrderPay(Channel channel, Message message) {
        MessageProperties properties = message.getMessageProperties();
        long deliveryTag = properties.getDeliveryTag();

        //1 获取消息的内容，并转换为字符串
        String payNotifyResultJsonString = new String(message.getBody());

        try {
            //2 调用业务层方法，修改秒杀订单的状态
            seckillOrderService.updateSeckillOrder(payNotifyResultJsonString);

            //3 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            //4 异常处理
            try {
                if (message.getMessageProperties().getRedelivered()) {
                    //消息确认两次都失败，直接丢弃
                    channel.basicReject(deliveryTag, false);
                }else {
                    //消息确认第一次失败，重试
                    channel.basicReject(deliveryTag, true);
                }
            } catch (Exception e1) {
                log.error("拒收消息发生异常，修改订单支付结果失败，支付通知报文为：" + payNotifyResultJsonString);
            }
            log.error("确认消息失败，修改订单支付结果失败，支付通知报文为：" + payNotifyResultJsonString);
        }
    }
}
